package cn.zmit.kuxi.fragment;

import java.util.HashMap;
import java.util.Map;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.holder.ListViewDataAdapter;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.loadmore.LoadMoreContainer;
import com.xdroid.widget.loadmore.LoadMoreDefaultFooterView;
import com.xdroid.widget.loadmore.LoadMoreHandler;
import com.xdroid.widget.loadmore.LoadMoreListViewContainer;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.AlreadyJoinrecordActivity;
import cn.zmit.kuxi.activity.HisCenterActivity;
import cn.zmit.kuxi.activity.JoinDetailActivity;
import cn.zmit.kuxi.activity.Joinrecord;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.entity.AlreadyPublicEntity;
import cn.zmit.kuxi.holder.AlreadyPublicHorlder;
import cn.zmit.kuxi.interfaces.OnListItemSelectListener;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.PtrHeader;

/** * @author @parameter * @return */
public class JoinRecordFragmentAlready extends Fragment {
	View fragment_joinView;
	@ViewInject(R.id.list_goods)
	private ListView list_goods;
	private ListViewDataAdapter<AlreadyPublicEntity> AlreadyPublicAdapter;
	String userid;
	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;
	/**
	 * 页码
	 */
	private int mPage = 1;
	@ViewInject(R.id.load_more_list_view_container)
	private LoadMoreListViewContainer mLoadMoreListViewContainer;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (fragment_joinView == null) {
			fragment_joinView = inflater.inflate(R.layout.fragment_goods,
					container, false);
		}
		ViewUtils.inject(this, fragment_joinView);
		Boolean haslogin = PreferenceHelper.readBoolean(getActivity(),
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (haslogin) {
			userid = PreferenceHelper.readString(getActivity(),
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		}
		initPtr();
		initView();
		initLoadMore();
		Button btn_gotop = (Button) fragment_joinView
				.findViewById(R.id.btn_gotop);
		btn_gotop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				list_goods.setSelection(0);
				initPtr();
			}
		});
		return fragment_joinView;
	}

	LoadMoreDefaultFooterView mFooterView;

	/**
	 * 初始化上拉刷新，分页显示
	 */
	private void initLoadMore() {
		mFooterView = mLoadMoreListViewContainer.useDefaultFooterRe(); // 使用默认的FooterView
		mLoadMoreListViewContainer.setLoadMoreHandler(new LoadMoreHandler() {

			@Override
			public void onLoadMore(LoadMoreContainer loadMoreContainer) {
				if (!mLoadMoreListViewContainer.isLoadError()) {
					mPage++;
				}
				getData();
			}
		});
	}

	/**
	 * 初始化下拉刷新
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(getActivity());
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {
						mFooterView.setVisibility(View.GONE);
						AlreadyPublicAdapter.removeAll();
						mPage = 1;
						getData();
					}

				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				// TODO Auto-generated method stub
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						list_goods, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}

	private void getData() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_id", userid);
		RequestTask.getInstance().doAlreadyPublic(getActivity(), mPage + "",
				map, new onRequestListener());
	}

	private void initView() {
		AlreadyPublicAdapter = new ListViewDataAdapter<AlreadyPublicEntity>();
		AlreadyPublicAdapter.setViewHolderClass(this,
				AlreadyPublicHorlder.class);
		TextView mHolderPlace = new TextView(getActivity()); // 占位作用，无意义，占据90dp高度，目的Listview位置向下移动45dp
		AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
				AbsListView.LayoutParams.MATCH_PARENT,
				(int) ScreenUtils.dpToPx(getActivity(), 1));
		mHolderPlace.setLayoutParams(layoutParams);
		mHolderPlace.setBackgroundColor(Color.parseColor("#FFFFFF"));
		list_goods.addHeaderView(mHolderPlace);// 为Listview添加占位符*/
		list_goods.setAdapter(AlreadyPublicAdapter);
		AlreadyPublicHorlder
				.setOnListItemSelectListener(new OnListItemSelectListener<AlreadyPublicEntity>() {

					@Override
					public void onlistItemSelect(int position,
							AlreadyPublicEntity itemData) {
						Intent intent = new Intent(getActivity(),
								JoinDetailActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("gp_id", itemData.getGp_id());
						bundle.putString("win_id", itemData.getWinner_id());
						intent.putExtras(bundle);
						startActivity(intent);
					}
				});
	}

	private class onRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);
			Boolean mIsEmpty = false; // 是否是空数据
			Boolean mHasMore = false; // 是否有更多数据待加载
			JsonData jsonData = JsonData.create(response);

			if (jsonData != null && jsonData.length() > 0) {
				JsonData data = jsonData.optJson("announced_record");
				int now_time = jsonData.optInt("now_time");
				if (data.length() > 0) {
					if (data.length() == 8) {
						mHasMore = true; // 有更多数据
					} else if (data.length() < 8) {
						mIsEmpty = false; // 有数据
						mHasMore = false; // 无更多数据
					}
					if (data != null && data.length() > 0) {

						for (int i = 0; i < data.length(); i++) {
							JsonData itemDate = data.optJson(i);
							String url = itemDate.optString("pic");
							String gp_id = itemDate.optString("gp_id");
							String title = itemDate.optString("phase");
							String time = itemDate.optString("announceOn");
							int oldtime = itemDate.optInt("unix_announceOn");
							String winner_id = itemDate.optString("winner_id");
							String winner_phone = itemDate
									.optString("winner_phone");
							int winner_buy_count = itemDate
									.optInt("winner_buy_count");
							String goodsName = itemDate.optString("name");
							String lucky_num = itemDate
									.optString("lucky_number");
							Log.e("now_time-old_time", now_time + "==="
									+ oldtime);
							AlreadyPublicEntity alreadyPublicEntity = new AlreadyPublicEntity(
									url, gp_id, title, time, winner_id,
									winner_phone, userid, goodsName, lucky_num,
									oldtime, now_time, winner_buy_count);
							AlreadyPublicAdapter.append(alreadyPublicEntity);
						}
					} else {
						mIsEmpty = true; // 空数据
						mHasMore = false; // 无更多数据
					}
					mLoadMoreListViewContainer.loadMoreFinish(mIsEmpty,
							mHasMore); // 判断是否加载更多
				}
			}
			ptr_view.refreshComplete();
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void onResume() {
		super.onResume();
	}
}
